package com.liser.southernstar.ui.activity;

import android.util.Log;
import android.view.View;
import android.widget.LinearLayout;

import androidx.coordinatorlayout.widget.CoordinatorLayout;
import androidx.recyclerview.widget.DefaultItemAnimator;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import com.google.android.material.bottomsheet.BottomSheetBehavior;
import com.kunminx.linkage.LinkageRecyclerView;
import com.liser.print.bluetooth.callback.SendCallback;
import com.liser.print.bluetooth.exceptions.BluetoothException;
import com.liser.southernstar.R;
import com.liser.southernstar.framework.helper.ToastHelper;
import com.liser.southernstar.net.observer.SimpleSubs;
import com.liser.southernstar.framework.ui.BaseActivity;
import com.liser.southernstar.collection.model.dto.GoodsFamilyDTO;
import com.liser.southernstar.net.Network;
import com.liser.southernstar.net.observer.NetworkSubs;
import com.liser.southernstar.collection.ui.widget.CarBottomView;
import com.liser.southernstar.model.mapper.ConversionFactory;
import com.liser.southernstar.model.vo.GoodsGroupedHeader;
import com.liser.southernstar.model.vo.GoodsGroupedItem;
import com.liser.southernstar.neleme.utils.ViewUtils;
import com.liser.southernstar.service.CustomerOrderPrintService;
import com.liser.southernstar.ui.adapter.GoodsOrderedAdapter;
import com.liser.southernstar.ui.adapter.GoodsPrimaryAdapter;
import com.liser.southernstar.ui.adapter.GoodsSecondaryAdapter;
import com.liser.southernstar.ui.widget.ElemeAddWidget;
import com.trello.rxlifecycle3.android.ActivityEvent;

import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.List;

import butterknife.BindView;
import butterknife.OnClick;
import io.reactivex.android.schedulers.AndroidSchedulers;
import io.reactivex.disposables.Disposable;
import io.reactivex.schedulers.Schedulers;

/**
 * @author LISER
 * @date 2020/1/10 22:18
 */
public class ElemeActivity extends BaseActivity {

    public static final String TAG = ElemeActivity.class.getName();

    @BindView(R.id.eleme_coordinator)
    CoordinatorLayout elemeCoordinator;

    @BindView(R.id.linkage)
    LinkageRecyclerView linkage;

    @BindView(R.id.car_cover_view)
    View carCoverView;

    @BindView(R.id.car_bottom_view)
    CarBottomView carBottomView;

    @BindView(R.id.car_popup_view)
    LinearLayout carPopupView;

    @BindView(R.id.car_ordered_recycler_view)
    RecyclerView carOrderedRecyclerView;

    private BottomSheetBehavior mBottomSheetBehavior;

    private ElemeAddWidget.OnAddClickListener onAddClickListener;

    private GoodsOrderedAdapter goodsOrderedAdapter;

    private GoodsPrimaryAdapter goodsPrimaryAdapter;

    private GoodsSecondaryAdapter goodsSecondaryAdapter;

    private SendCallback sendCallback;

    @Override
    protected int onLayout() {
        return R.layout.activity_eleme;
    }

    @Override
    protected void onView() {
        initListener();
        initBehavior();
        initRecycleView();
        initNet();
    }

    @OnClick(R.id.car_limit)
    public void goodsAccount() {
        CustomerOrderPrintService.getInstance()
                .orderPrinting(goodsOrderedAdapter.getData(), sendCallback)
                .compose(bindUntilEvent(ActivityEvent.DESTROY))
                .subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe((new SimpleSubs<String>() {
                    @Override
                    public void onSubscribe(Disposable d) {
                        ToastHelper.show("商品打印进行中....");
                    }

                    @Override
                    public void onSuccess(String message) {
                        ToastHelper.show("打印商品进行中....");
                    }

                    @Override
                    public void onError(Throwable e) {
                        Log.e(TAG, "商品打印出错：", e);
                        if (e instanceof BluetoothException) {
                            ToastHelper.show(e.getMessage());
                        }
                    }
                }));
    }

    private void initListener() {
        onAddClickListener = new ElemeAddWidget.OnAddClickListener() {
            @Override
            public void onAddClick(View view, GoodsGroupedItem goodsGroupedItem) {
                ViewUtils.addTvAnim(view, carBottomView.carLoc, ElemeActivity.this, elemeCoordinator);
                refreshCart(goodsGroupedItem);
            }

            @Override
            public void onSubClick(GoodsGroupedItem goodsGroupedItem) {
                refreshCart(goodsGroupedItem);
            }
        };

        goodsPrimaryAdapter = new GoodsPrimaryAdapter()
                .setOnItemClickListener((holder, view, title) -> {

                });

        goodsSecondaryAdapter = new GoodsSecondaryAdapter();
        goodsSecondaryAdapter.setOnAddClickListener(onAddClickListener);

        sendCallback = new SendCallback() {
            @Override
            public void sendSuccess() {
                ToastHelper.show("打印成功");
            }

            @Override
            public void sendError(Throwable throwable) {
                ToastHelper.show("打印失败");
            }
        };
    }

    private void initBehavior() {
        mBottomSheetBehavior = BottomSheetBehavior.from(carPopupView);
        carBottomView.setBehavior(mBottomSheetBehavior, carCoverView);
    }

    private void initRecycleView() {
        carOrderedRecyclerView.setLayoutManager(new LinearLayoutManager(ElemeActivity.this));
        if (carOrderedRecyclerView.getItemAnimator() != null) {
            ((DefaultItemAnimator) carOrderedRecyclerView.getItemAnimator()).setSupportsChangeAnimations(false);
        }
        goodsOrderedAdapter = new GoodsOrderedAdapter(onAddClickListener);
        goodsOrderedAdapter.bindToRecyclerView(carOrderedRecyclerView);
    }

    private void initNet() {
        Network.api().getDataByBiz("412929567079170008")
                .compose(bindToLifecycle())
                .subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(new NetworkSubs<List<GoodsFamilyDTO>>() {
                    @Override
                    public void onSuccess(List<GoodsFamilyDTO> data) {
                        List<GoodsGroupedHeader> goodsGroupedHeaderList = new ArrayList<>();
                        for (GoodsFamilyDTO goodsFamilyDTO : data) {
                            List<GoodsGroupedHeader> goodsGroupedItemInnerList = ConversionFactory.goodsGroupedHeader(goodsFamilyDTO);
                            goodsGroupedHeaderList.addAll(goodsGroupedItemInnerList);
                        }
                        // noinspection unchecked
                        linkage.init(goodsGroupedHeaderList, goodsPrimaryAdapter, goodsSecondaryAdapter);
                    }
                });
    }

    private void refreshCart(GoodsGroupedItem goodsGroupedItem) {
        BigDecimal amount = new BigDecimal(0.0);
        int total = 0;
        boolean ordered = false;
        if (mBottomSheetBehavior.getState() == BottomSheetBehavior.STATE_EXPANDED) {
            // 根据底部列表是否显示 通知商品列表数据变化
            linkage.getSecondaryAdapter().notifyDataSetChanged();
        }

        List<GoodsGroupedItem> data = goodsOrderedAdapter.getData();
        int p = -1;

        // 更新已经添加的列表项的总数
        for (int i = 0; i < data.size(); i++) {
            GoodsGroupedItem goodsGroupedItemInner = data.get(i);
            boolean equals = goodsGroupedItemInner.getId().equals(goodsGroupedItem.getId());
            if (equals) {
                if (goodsGroupedItemInner.getSelectCount() == 0) {
                    p = i;
                }
                goodsGroupedItemInner.setSelectCount(goodsGroupedItem.getSelectCount());
                goodsOrderedAdapter.notifyItemChanged(i);
                ordered = true;
            }
            total += goodsGroupedItemInner.getSelectCount();
            amount = amount.add(goodsGroupedItemInner.getPrice().multiply(BigDecimal.valueOf(goodsGroupedItemInner.getSelectCount())));
        }

        if (p >= 0) {
            goodsOrderedAdapter.remove(p);
        }

        // 列表中未添加则添加
        if (!ordered) {
            goodsOrderedAdapter.addData(goodsGroupedItem);
            total += goodsGroupedItem.getSelectCount();
            amount = amount.add(goodsGroupedItem.getPrice().multiply(BigDecimal.valueOf(goodsGroupedItem.getSelectCount())));
        }

        carBottomView.showBadge(total);
        carBottomView.updateAmount(amount);
    }

}
